package com.study.common.util;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.util.CollectionUtils;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;


import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

import javax.imageio.ImageIO;

public class PdfUtil {
    /**
     * 将pdf文件转换为Base64编码
     * @author hw
     * @date 2023/3/14 9:39:12
     * @param file:
     * @return java.lang.String
     */
    public static String pdfToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin =null;
        BufferedInputStream bin =null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout =null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 图片转PDF
     * @param images 图片的url
     * @throws Exception
     */
    public static String imageToPdf(List<String> images, String target) throws Exception {
        Document document = new Document();
        // 设置文档页边距
        document.setMargins(0, 0, 0, 0);
        FileOutputStream fos = null;
        File outFile;
        try {
            outFile = File.createTempFile(target, ".pdf");//创建临时文件
            fos = new FileOutputStream(outFile);
            PdfWriter.getInstance(document, fos);
            // 打开文档
            document.open();

            if(!CollectionUtils.isEmpty(images)){
                images.forEach(url->{
                    try {
                        Image image = getImage(url);
                        // 设置页面宽高与图片一致
                        Rectangle rectangle = new Rectangle(image.getScaledWidth(), image.getScaledHeight());
                        document.setPageSize(rectangle);
                        // 新建一页添加图片
                        document.newPage();
                        document.add(image);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            // 关闭文档
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outFile.getCanonicalPath();
    }

    /**
     * 获取图片
     * @param url
     * @return
     * @throws BadElementException
     * @throws IOException
     */
    private static Image getImage(String url) throws BadElementException, IOException {
        // 获取图片的宽高
        Image image = Image.getInstance(url);
        // 调整图片缩放
        image.scaleToFit(600,600);
        // 图片居中
        image.setAlignment(Image.ALIGN_CENTER);
        return image;
    }

    /**
     * pdf合并拼接
     * @param files 文件列表
     * @param targetPath 合并到
     * @return
     * @throws IOException
     */
    public static File mulFile2One(List<File> files,String targetPath) throws IOException{
        // pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if(f.exists() && f.isFile()){
                // 循环添加要合并的pdf
                mergePdf.addSource(f);
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(targetPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new File(targetPath);
    }

    /**
     * 转换全部的pdf
     * @param file 文件地址
     */
    public static File pdfToImage(File file) {
        //图片类型
        String type = "jpg";
        // 将pdf装图片 并且自定义图片得格式大小
        //新file
        File newFile = new File(file.getPath()+"_"+"."+type);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // Windows native DPI
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                //产生缩略图
                // BufferedImage srcImage = resize(image, 240, 240);
                ImageIO.write(image, type, newFile);
                //清除
                //image.flush();
                //关闭
                doc.close();
                //只要第一面
                return newFile;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     *自由确定起始页和终止页
     * @param fileAddress 文件地址
     * @param filename pdf文件名
     * @param indexOfStart 开始页  开始转换的页码，从0开始
     * @param indexOfEnd 结束页  停止转换的页码，-1为全部
     * @param type 图片类型
     */
    public static void pdf2png(String fileAddress,String filename,int indexOfStart,int indexOfEnd,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fileAddress+"\\"+filename+".pdf");
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = indexOfStart; i < indexOfEnd; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        /*File file = new File("D:\\cs.pdf");
        String pdf = PdfUtil.pdfToBase64(file);
        Map map = new HashMap();
        map.put("pdf", pdf);
        System.out.println(JSONUtil.toJsonStr(map));*/

        /*System.out.println(Validator.isMobile("18679155715"));
        System.out.println(Validator.isMobile("15079088878"));
        System.out.println(Validator.isMobile("18070123458"));
        System.out.println(Validator.isMobile("11170123458"));

        if(!Validator.isMobile("18070123458".trim())){
            throw new RuntimeException("请传递正确的手机号");
        }*/

//        String url1 = "http://10.56.0.180/group2/M02/BE/28/CjhkSGbNZ-2AQRHzAAkTSVeWUDA772.pdf";
//        String url2 = "http://10.56.0.180/group2/M02/BE/27/CjhkSGbNZ-qAcDIPAAkSOIWTm2s464.pdf";

        /*String url1 = "D:\\111.pdf";
        String url2 = "D:\\222.pdf";

        File file1 = new File(url1);
        File file2 = new File(url2);
        List<File> files = new ArrayList<>();
        files.add(file1);
        files.add(file2);

        String path = "D:\\all_file.pdf";

        PdfUtil.mulFile2One(files, path);*/

        /*System.out.println(FileNameUtil.getPrefix("汇仁基金会2022年专项审计报告.pdf"));
        System.out.println(FileNameUtil.getSuffix("汇仁基金会2022年专项审计报告.pdf"));
        System.out.println(FileNameUtil.getPrefix("/group2/M00/B3/FE/CjhkNWRwXXKAAPkzADKQ3iQmIf8874.rar"));
        System.out.println(FileNameUtil.getSuffix("/group2/M00/B3/FE/CjhkNWRwXXKAAPkzADKQ3iQmIf8874.rar"));*/

        /*System.out.println(String.valueOf(IdcardUtil.getGenderByIdCard("362422199810034312")));
        System.out.println(String.valueOf(IdcardUtil.getGenderByIdCard("360111201008043046")));

        int i = 300;
        int j = 300;
        System.out.println();*/


        String path = "D:\\all_file (2).pdf";
        PdfUtil.pdfToImage(new File(path));

    }
}
